package com.gress.shop.controller.login;

import com.gress.shop.annotation.FireLogger;
import com.gress.shop.bo.LogInfo;
import com.gress.shop.bo.Member;
import com.gress.shop.bo.Role;
import com.gress.shop.service.IAccessLogService;
import com.gress.shop.service.IMenuService;
import com.gress.shop.service.IRoleService;
import com.wordnik.swagger.annotations.Api;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created xiongwen with 2018/1/24 16:37
 * Description:
 */
@Controller
@Api("登录")
public class LoginController {
    @Resource
    private IMenuService menuService;
    @Resource
    private IRoleService roleService;

    @RequestMapping({"/home", "/"})
    @FireLogger("主页")
    public String home(HttpSession session, Model model) {
        Subject subject = SecurityUtils.getSubject();
        Member principal = (Member) subject.getPrincipal();
        session.setAttribute("MenuTree", menuService.buildMenuTree(principal.getEmail()));
        session.setAttribute("memberUser", principal);
        Role role = roleService.queryByEmail(principal.getEmail());
        if (role == null) {
            role = new Role();
            role.setName("访客");
        }
        session.setAttribute("loginRole", role);

        return "common/index";
    }

    @RequestMapping("lock_screen")
    public String LockSereen(){
        return "login/lockscreen";
    }

    @RequestMapping("/login/login")
    public String loginSubmit(HttpServletRequest request, Model model) {
        // shiro在认证过程中出现错误后将异常类路径通过request返回
        Subject subject = SecurityUtils.getSubject();
        boolean isAuthenticated = subject.isAuthenticated();
        if (isAuthenticated) {
            return "common/index";
        }
        String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
        String msg = "";
        if (exceptionClassName != null) {
            if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
                System.out.println("账号不存在");
                msg = "账号不存在";
            } else if (IncorrectCredentialsException.class.getName().equals(
                    exceptionClassName)) {
                System.out.println("用户名/密码错误");
                msg = "用户名/密码错误";
            } else if ("randomCodeError".equals(exceptionClassName)) {
                msg = "验证码错误/密码错误";
                System.out.println("验证码错误");
            } else {
                msg = "未知错误";
                System.out.println("未知错误");
            }
            model.addAttribute("msg", msg);
        }
        return "/login/login_from";
    }

}
